package com.robert.jiaoziplayer.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.neliveplayer.sdk.NELivePlayer;
import com.netease.neliveplayer.sdk.constant.NEType;
import com.robert.jiaoziplayer.R;
import com.robert.jiaoziplayer.media.NEVideoView;
import com.robert.jiaoziplayer.recevier.NEPhoneCallStateObserver;
import com.robert.jiaoziplayer.recevier.NEScreenStateObserver;
import com.robert.jiaoziplayer.recevier.Observer;

public class NEVideoPlayerActivity extends Activity {
    public final static String TAG = NEVideoPlayerActivity.class.getSimpleName();
    private final static String MEDIA_TYPE = "livestream";
    public NEVideoView mVideoView;  //用于画面显示

    private TextView mFileName; //文件名称

    private boolean mBackPressed;

    private RelativeLayout mPlayToolbar;
    private NEScreenStateObserver mScreenStateObserver;
    private boolean isScreenOff;
    private boolean isBackground;
    private FrameLayout mFlVideoPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "on create");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        mFlVideoPlayer = findViewById(R.id.fl_video_player);
        NEPhoneCallStateObserver.getInstance().observeLocalPhoneObserver(localPhoneObserver, true);
        mScreenStateObserver = new NEScreenStateObserver(this);
        mScreenStateObserver.observeScreenStateObserver(screenStateObserver, true);

        //接收MainActivity传过来的参数
        String videoPath = "rtmp://vbd018e20.live.126.net/live/052e433082bf48529c0893ebe5d429ae";

        Log.i(TAG, "videoPath = " + videoPath);


        Intent intent = getIntent();
        String intentAction = intent.getAction();
        if (!TextUtils.isEmpty(intentAction) && intentAction.equals(Intent.ACTION_VIEW)) {
            videoPath = intent.getDataString();
            Log.i(TAG, "videoPath = " + videoPath);
        }


        ImageButton playBack = findViewById(R.id.player_exit);
        playBack.getBackground().setAlpha(0);

        mPlayToolbar = findViewById(R.id.play_toolbar);
        mPlayToolbar.setVisibility(View.INVISIBLE);

        View buffer = findViewById(R.id.buffering_prompt);

        mVideoView = findViewById(R.id.video_view);

        mVideoView.setBufferStrategy(NEType.NELPLOWDELAY); //直播低延时
        mVideoView.setBufferingIndicator(buffer);
        mVideoView.setMediaType(MEDIA_TYPE);
        mVideoView.setHardwareDecoder(true);
        /*
          mEnableBackgroundPlay 控制退到后台或者锁屏时是否继续播放，开发者可根据实际情况灵活开发,我们的示例逻辑如下：
          <p>
          mEnableBackgroundPlay 为 false时，
          使用软件编码或者硬件解码，点播进入后台暂停，进入前台恢复播放，直播进入后台停止播放，进入前台重新拉流播放
          <p>
          mEnableBackgroundPlay 为 true时，
          使用软件编码，点播和直播进入后台不做处理，继续播放
          使用硬件解码，点播和直播进入后台统一停止播放，进入前台的话重新拉流播放
         */
        boolean enableBackgroundPlay = true;
        mVideoView.setEnableBackgroundPlay(enableBackgroundPlay);
        mVideoView.setVideoPath(videoPath);
        mVideoView.requestFocus();
        mVideoView.start();
        mVideoView.setOnErrorListener(new NELivePlayer.OnErrorListener() {
            @Override
            public boolean onError(NELivePlayer neLivePlayer, int i, int i1) {
                return false;
            }
        });

        mVideoView.setOnCompletionListener(new NELivePlayer.OnCompletionListener() {
            @Override
            public void onCompletion(NELivePlayer neLivePlayer) {

            }
        });

        mVideoView.setOnInfoListener(new NELivePlayer.OnInfoListener() {
            @Override
            public boolean onInfo(NELivePlayer neLivePlayer, int i, int i1) {
                return false;
            }
        });

        mFlVideoPlayer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
    }

    Observer<Integer> localPhoneObserver = new Observer<Integer>() {
        @Override
        public void onEvent(Integer phoneState) {
            if (phoneState == TelephonyManager.CALL_STATE_IDLE) {
                mVideoView.restorePlayWithCall();
            } else if (phoneState == TelephonyManager.CALL_STATE_RINGING) {
                mVideoView.stopPlayWithCall();
            } else {
                Log.i(TAG, "localPhoneObserver onEvent " + phoneState);
            }

        }
    };

    Observer<NEScreenStateObserver.ScreenStateEnum> screenStateObserver = new Observer<NEScreenStateObserver.ScreenStateEnum>() {
        @Override
        public void onEvent(NEScreenStateObserver.ScreenStateEnum screenState) {
            if (screenState == NEScreenStateObserver.ScreenStateEnum.SCREEN_ON) {
                Log.i(TAG, "onScreenOn ");
                if (isScreenOff) {
                    mVideoView.restorePlayWithForeground();
                }
                isScreenOff = false;
            } else if (screenState == NEScreenStateObserver.ScreenStateEnum.SCREEN_OFF) {
                Log.i(TAG, "onScreenOff ");
                isScreenOff = true;
                if (!isBackground) {
                    mVideoView.stopPlayWithBackground();
                }
            } else {
                Log.i(TAG, "onUserPresent ");
            }

        }
    };

    OnClickListener mOnClickEvent = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.player_exit) {
                Log.i(TAG, "player_exit");
                mBackPressed = true;
            }
        }
    };

    public void setFileName(String name) { //设置文件名并显示出来
        if (mFileName != null) {
            mFileName.setText(name);
            mFileName.setGravity(Gravity.CENTER);
        }
    }

    @Override
    public void onBackPressed() {
        Log.i(TAG, "onBackPressed");
        mBackPressed = true;
        finish();
        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        Log.i(TAG, "NEVideoPlayerActivity onPause");
        super.onPause();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "NEVideoPlayerActivity onDestroy");
        mVideoView.destroy();
        super.onDestroy();
        NEPhoneCallStateObserver.getInstance().observeLocalPhoneObserver(localPhoneObserver, false);
        mScreenStateObserver.observeScreenStateObserver(screenStateObserver, false);
        mScreenStateObserver = null;
    }

    @Override
    protected void onStart() {
        Log.i(TAG, "NEVideoPlayerActivity onStart");
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "NEVideoPlayerActivity onResume");
        super.onResume();
        if (!mBackPressed && !isScreenOff && isBackground) {
            isBackground = false;
        }
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "NEVideoPlayerActivity onStop");
        super.onStop();
        if (!mBackPressed && !isScreenOff) {
            mVideoView.stopPlayWithBackground();
            isBackground = true;
        }
    }


    @Override
    protected void onRestart() {
        Log.i(TAG, "NEVideoPlayerActivity onRestart");
        super.onRestart();
    }
}